#user.py
import random
import re
import smtplib
from flask_mail import Mail, Message
from flask import Blueprint, redirect,render_template, request, jsonify, session, url_for,flash
from app.models.base import db
from app.models.student import Student
from app.models.teacher import Teacher
from app.models.admin import Admin
from sqlalchemy import or_,and_,all_,any_
from flask import current_app
userBP = Blueprint('user',__name__)
def generate_verification_code():
    # 生成一个0-9之间的随机整数，范围是[0, 9999]
    verification_code = random.randint(0, 9999)
    return str(verification_code).zfill(4) 
def send_email(mail_instance,user_email, user_name,vcode):
        message = Message('Registration Confirmation', sender='zj2585306788@163.com', recipients=[user_email])
        message.body = f"""
        Dear {user_name},

        Thank you for registering on our platform.

        Please enter the following verification code to verify your email address:

        {vcode}

        This code will expire in 24 hours.

        Sincerely,
        The UIC Platform Team
        """
        mail_instance.send(message)

@userBP.route('/login',methods=['GET','POST'])
def login():
    if request.method == 'GET':
        return render_template('login-9.html',title='Sample Login',header='Sample Case')
    else:

        email = request.form.get('email')
        _password = request.form.get('password')

        print(email, _password)

        if re.search(r"@mail\.uic\.edu\.hk$|@mail\.uic\.edu\.cn$", email): #正则
            result = Student.query.filter(and_(Student.email == email,Student._password == _password)).first()
        elif re.search(r"@uic\.edu\.hk$", email):
            result = Teacher.query.filter(and_(Teacher.email == email,Teacher._password == _password)).first()
        elif re.search(r"@uic\.edu\.admin$", email):
            print("result.name")
            result = Admin.query.filter(and_(Admin.email == email,Admin._password == _password)).first()
            
        else:
            flash('Invalid email!', 'danger')
            render_template('login-9.html', title='Sample Login', header='Sample Case')
        
        if result:
            #print(result.name)
            #print(result._password)
            print("1111")
            if isinstance(result, Student):
                session['name'] = result.name
                session['id'] = result.id
                return redirect(url_for('student.get_student'))  # 假设你有一个名为user.student的路由
            elif isinstance(result, Teacher):
                session['name'] = result.name
                session['id'] = result.id
                return redirect(url_for('teacher.get_teacher'))  # 如果有teacher路由
            elif isinstance(result, Admin):
                session['name'] = result.name
                session['id'] = result.id
                return redirect(url_for('admin.view_add_course_requests'))  # 如果有admin路由
        else:
            flash('Password is wrong!', 'danger')  # 提示登录失败
            return render_template('login-9.html', title='Sample Login', header='Sample Case')

@userBP.route('/logout')
def logout():
    session.pop('name', None)
    session.pop('id', None)
    return redirect(url_for('user.login'))

@userBP.route('/register',methods=['GET','POST'])
def register():
    if request.method == 'GET':
        return render_template('register-9.html',title='Sample Register',header='Sample Case')
    else:
        email = request.form.get('email')
        _password = request.form.get('password')
        name = request.form.get('name')
        print(email, _password,name)
        if re.search(r"@mail\.uic\.edu\.cn$|@mail\.uic\.edu\.hk$", email):  #正则
            if Student.query.filter(Student.email == email).first(): # 邮箱重复
                flash('Email repeat!', 'danger')
                return render_template('register-9.html', title='Sample Login', header='Sample Case')
            else:
                vcode=generate_verification_code()
                print(vcode)
                mail = current_app.extensions['mail']
                send_email(mail, email, name,vcode)
                session['vcode'] = vcode
                session['email'] = email
                session['name'] = name
                session['_password'] = _password
                session['type']="Student"
                return redirect(url_for('user.verify'))
                    
                    #return redirect(url_for('mail.send_email',user_email=email,user_name=name))
        if re.search(r"@uic\.edu\.hk$", email):
            if Teacher.query.filter(Teacher.email == email).first(): # 邮箱重复
                flash('Email repeat!', 'danger')
                return render_template('register-9.html', title='Sample Login', header='Sample Case')
            else:
                vcode=generate_verification_code()
                print(vcode)
                mail = current_app.extensions['mail']
                send_email(mail, email, name,vcode)
                session['vcode'] = vcode
                session['email'] = email
                session['name'] = name
                session['_password'] = _password
                session['type']="teacher"
                return redirect(url_for('user.verify'))
        elif email=='admin':
            if Admin.query.filter(Admin.email == email).first(): # 邮箱重复
                flash('Email repeat!', 'danger')
                return render_template('register-9.html', title='Sample Login', header='Sample Case')
            else:
                vcode=generate_verification_code()
                print(vcode)
                mail = current_app.extensions['mail']
                send_email(mail, email, name,vcode)
                session['vcode'] = vcode
                session['email'] = email
                session['name'] = name
                session['_password'] = _password
                session['type']="admin"
                return redirect(url_for('user.verify'))
        return redirect(url_for('user.login'))

@userBP.route('/verify',methods=['GET','POST'])
def verify():
    if request.method == 'GET':
        return render_template('otp-9.html',title='Sample Verify',header='Sample Case')
    else:
        d1=request.form.get('d1')
        d2=request.form.get('d2')
        d3=request.form.get('d3')
        d4=request.form.get('d4')
        vcode_ = d1+d2+d3+d4
        vcode = session.get('vcode')
        password = session.get('_password')
        email = session.get('email')
        name = session.get('name')
        type = session.get('type')
        print(vcode_)
        if vcode == vcode_:
            if type=="Student":
                with db.auto_commit():
                    user = Student(name ,email,password)
        # 数据库的insert操作
                    db.session.add(user)
            if type=="teacher":
                with db.auto_commit():
                    user = Teacher(name ,email,password)
        # 数据库的insert操作
                    db.session.add(user)
            if type=="admin":
                with db.auto_commit():
                    user = Admin(name ,email,password)
        # 数据库的insert操作
                    db.session.add(user)
            return redirect(url_for('user.login'))
        else:
            print("wrong")
            return redirect(url_for('user.register'))

        